<template>
	<div class="system-menu-dialog-container">
		<el-dialog v-model="state.dialog.isShowDialog" :title="state.dialog.title" width="769px">
			<el-form ref="menuDialogFormRef" :model="state.ruleForm" :rules="rules" label-width="80px" size="default">
				<el-row :gutter="35">
					<el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24" class="mb20">
						<el-form-item label="上级菜单" prop="parentId">
							<el-cascader v-model="state.ruleForm.parentId" :options="state.menuData"
								:props="{ checkStrictly: true, value: 'id', label: 'title', emitPath: false }" class="w100" clearable
								placeholder="请选择上级菜单">
								<template #default="{ node, data }">
									<span>{{ data.title }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24" class="mb20">
						<el-form-item label="菜单类型" prop="type">
							<el-radio-group v-model="state.ruleForm.type">
								<el-radio label="menu">菜单</el-radio>
								<el-radio label="btn">按钮</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
						<el-form-item label="菜单名称" prop="title">
							<el-input v-model="state.ruleForm.title" clearable placeholder="格式：message.router.xxx"></el-input>
						</el-form-item>
					</el-col>
					<template v-if="state.ruleForm.type === 'menu'">
						<el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
							<el-form-item label="路由名称" prop="name">
								<el-input v-model="state.ruleForm.name" clearable placeholder="路由中的 name 值"></el-input>
							</el-form-item>
						</el-col>
						<el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
							<el-form-item label="路由路径" prop="path">
								<el-input v-model="state.ruleForm.path" clearable placeholder="路由中的 path 值"></el-input>
							</el-form-item>
						</el-col>
						<el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
							<el-form-item label="重定向" prop="redirect">
								<el-input v-model="state.ruleForm.redirect" clearable placeholder="请输入路由重定向"></el-input>
							</el-form-item>
						</el-col>
						<el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
							<el-form-item label="菜单图标" prop="icon">
								<IconSelector v-model="state.ruleForm.icon" placeholder="请输入菜单图标" />
							</el-form-item>
						</el-col>
						<el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
							<el-form-item label="组件路径" prop="component">
								<el-input v-model="state.ruleForm.component" clearable placeholder="组件路径"></el-input>
							</el-form-item>
						</el-col>
						<el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
							<el-form-item label="链接地址" prop="link">
								<el-input v-model="state.ruleForm.link" clearable placeholder="外链/内嵌时链接地址（http:xxx.com）"></el-input>
							</el-form-item>
						</el-col>
					</template>
					<el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
						<el-form-item label="权限标识" prop="permission">
							<el-input v-model="state.ruleForm.permission" clearable placeholder="请输入权限标识"></el-input>
						</el-form-item>
					</el-col>
					<el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
						<el-form-item label="菜单排序" prop="sort">
							<el-input-number v-model="state.ruleForm.sort" class="w100" controls-position="right" placeholder="请输入排序" />
						</el-form-item>
					</el-col>
					<template v-if="state.ruleForm.type === 'menu'">
						<el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
							<el-form-item label="是否隐藏" prop="hide">
								<el-radio-group v-model="state.ruleForm.hide">
									<el-radio :label="1">隐藏</el-radio>
									<el-radio :label="0">不隐藏</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
							<el-form-item label="页面缓存" prop="keepAlive">
								<el-radio-group v-model="state.ruleForm.keepAlive">
									<el-radio :label="1">缓存</el-radio>
									<el-radio :label="0">不缓存</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
							<el-form-item label="是否固定" prop="affix">
								<el-radio-group v-model="state.ruleForm.affix">
									<el-radio :label="1">固定</el-radio>
									<el-radio :label="0">不固定</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
							<el-form-item label="是否内嵌" prop="iframe">
								<el-radio-group v-model="state.ruleForm.iframe">
									<el-radio :label="1">是</el-radio>
									<el-radio :label="0">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button size="default" @click="onCancel">取 消</el-button>
					<el-button size="default" type="primary" @click="onSubmit(menuDialogFormRef)">{{ state.dialog.submitTxt
					}}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" name="systemMenuDialog" setup>
import { defineAsyncComponent, nextTick, onMounted, reactive, ref } from 'vue';
import { storeToRefs } from 'pinia';
import { useRoutesList } from '/@/stores/routesList';
import { i18n } from '/@/i18n/index';
import { Session } from '/@/utils/storage';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { useMenuApi } from '/@/api/sys/menu';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 引入组件
const IconSelector = defineAsyncComponent(() => import('/@/components/iconSelector/index.vue'));

// 定义变量内容
const menuDialogFormRef = ref();
const stores = useRoutesList();
const { routesList } = storeToRefs(stores);
const state = reactive({
	// 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由菜单格式
	ruleForm: {
		parentId: '', // 上级菜单
		type: 'menu', // 菜单类型
		path: '', // 菜单路径
		name: '', // 路由名称
		title: '', // 菜单名称
		component: '', // 组件路径
		redirect: '', // 重定向路径
		icon: '', // 图标信息
		link: '', // 链接地址
		hide: 0, // 是否隐藏
		keepAlive: 1, // 是否缓存
		affix: 0, // 是否固定
		iframe: 0, //是否外链
		sort: 0, // 菜单排序
		permission: '', // 权限标识
	},
	menuData: [] as RouteItems, // 上级菜单数据
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});
const rules = reactive<FormRules>({
	title: [{ required: true, message: '不能为空', trigger: 'blur' }],
	type: [{ required: true, message: '不能为空', trigger: 'blur' }],
});

// 获取 pinia 中的路由
const getMenuData = (routes: RouteItems) => {
	const arr: RouteItems = [];
	routes.map((val: RouteItem) => {
		val['title'] = i18n.global.t(val.meta?.title as string);
		arr.push({ ...val });
		if (val.children) getMenuData(val.children);
	});
	return arr;
};
// 打开弹窗
const openDialog = (type: string, row?: any) => {
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
	if (type === 'edit') {
		state.dialog.title = '修改菜单';
		state.dialog.submitTxt = '修 改';
	} else {
		state.dialog.title = '新增菜单';
		state.dialog.submitTxt = '新 增';
	}
	nextTick(() => {
		if (type === 'edit') {
			state.ruleForm = Object.assign(state.ruleForm, row);
		} else {
			menuDialogFormRef.value.resetFields()
			state.ruleForm.parentId = row ? row.id : '';
		}
	});
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid) => {
		if (valid) {
			if (state.dialog.type === 'add') {
				useMenuApi()
					.addRecord(state.ruleForm)
					.then((res) => {
						closeDialog(); // 关闭弹窗
						ElMessage.success(res.msg || '新增成功');
						emit('refresh');
						Session.remove('userInfo')
						initBackEndControlRoutes();
					});
			} else if (state.dialog.type === 'edit') {
				useMenuApi()
					.updateRecord(state.ruleForm)
					.then((res) => {
						closeDialog(); // 关闭弹窗
						ElMessage.success(res.msg || '新增成功');
						emit('refresh');
					});
			}
		}
	});
};
// 页面加载时
onMounted(() => {
	state.menuData = getMenuData(routesList.value);
});

// 暴露变量
defineExpose({
	openDialog,
});
</script>